import cv2

cap=cv2.VideoCapture(r'C:\Users\ASUS\Desktop\1.avi')
#设定角点检测和光流参数
feature_params=dict(maxCorners=100,qualityLevel=0.3,minDistance=7,blockSize=7)
lk_params=dict(winSize=(15,15),maxLevel=2,criteria=(cv2.TERM_CRITERIA_COUNT,10,0.03))

#计算第一帧特征点
ret,prev=cap.read()
prevGray=cv2.cvtColor(prev,cv2.COLOR_BGR2GRAY)
p0=cv2.goodFeaturesToTrack(prevGray,mask=None,**feature_params)

while True:
    ret,frame=cap.read()
    if not ret:
        break
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    p1,st,err=cv2.calcOpticalFlowPyrLK(prevGray,gray,p0,None,**lk_params)#计算光流
    #选取置信度高的特征点
    goodPoints=p1[st==1]
    goodPrevPoints=p0[st==1]

    res=frame.copy()
    drawColor=(0,0,255)
    for i,(cur,prev)in enumerate(zip(goodPoints,goodPrevPoints)):
        x0,y0=cur.ravel()
        x1,y1=prev.ravel()
        cv2.line(res,(x0,y0),(x1,y1),drawColor)
        cv2.circle(res,(x0,y0),3,drawColor)

    prevGray=gray.copy()
    p0=goodPoints.reshape(-1,1,2)

    cv2.imshow('检测结果',res)

    key=cv2.waitKey(30)
    if key==27:
        break

cap.release()
cv2.destroyAllWindows()

